package com.jxlc.framework.oauth2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jxlc.common.exception.GlobalException;
import com.jxlc.common.utils.uuid.IdUtils;
import com.jxlc.framework.oauth2.domain.OAuth2RefreshToken;
import com.jxlc.framework.oauth2.domain.dto.RefreshTokenDto;
import com.jxlc.framework.oauth2.enums.LoginType;
import com.jxlc.framework.oauth2.mapper.FieldOAuth2RefreshTokenMapper;
import com.jxlc.framework.oauth2.service.FieldOAuth2RefreshTokenService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.List;

/**
 *
 * OAuth2.0 Token Service 实现类
 *
 */
@Service
public class FieldOAuth2RefreshTokenServiceImpl extends ServiceImpl<FieldOAuth2RefreshTokenMapper, OAuth2RefreshToken>
		implements FieldOAuth2RefreshTokenService {

	@Override
	public OAuth2RefreshToken createRefreshToken(RefreshTokenDto dto) {
		LoginType loginType = dto.getLoginType();
		Assert.notNull(loginType, "登录类型不能为空");
		OAuth2RefreshToken refreshToken = new OAuth2RefreshToken();
		refreshToken.setRefreshToken(IdUtils.fastSimpleUUID());
		refreshToken.setClientId(dto.getClientId());
		refreshToken.setUserId(dto.getUserId());
		refreshToken.setLoginType(dto.getLoginType().name());
		if (dto.getExpiresTime() == null) {
			dto.setExpiresTime(30 * 2 * 12);//默认12小时有效期
		}
		refreshToken.setExpiresTime(LocalDateTime.now().plusMinutes(dto.getExpiresTime()));
		refreshToken.setCreateTime(LocalDateTime.now());
		this.save(refreshToken);
		return refreshToken;
	}

	@Override
	public OAuth2RefreshToken getByRefreshToken(String refreshToken) {
		List<OAuth2RefreshToken> list = this.list(
				new LambdaQueryWrapper<OAuth2RefreshToken>()
						.eq(OAuth2RefreshToken::getRefreshToken, refreshToken));
		if (list.isEmpty()) {
			return null;
		}
		if (list.size() != 1) {
			throw new GlobalException("refreshToken expected one, but found more than one ");
		}
		return list.get(0);
	}

}
